package com.metroinfo.workers;

import java.io.*;
import java.nio.*;
import java.nio.channels.SocketChannel;

import com.metroinfo.infrastructure.MainDataStructure;
import com.metroinfo.kernel.ProcessData;
import com.metroinfo.kernel.data.ResponseData;
import com.metroinfo.parser.CommandParser;
import com.metroinfo.parser.GeneralSettings;
import com.metroinfo.parser.data.GeneralRequest;

/**
 * Primary driver class used by blocking Servers to receive, prepare, send, and
 * shutdown requests.
 * 
 * @author Mark Reinhold
 * @author Brad R. Wetmore
 * @version 1.4, 10/01/12
 */
public class RequestServicerBuffer implements Runnable {

	private SocketChannel cio;
	private MainDataStructure mainDataStructure;
	private ByteBuffer bb;

	public RequestServicerBuffer(SocketChannel cio, MainDataStructure mds, ByteBuffer byteBuffer) {
		this.cio = cio;
		this.mainDataStructure = mds;
		
		bb = ByteBuffer.allocate(20); 
		//this.bb = ByteBuffer.allocate(byteBuffer.capacity());
		//this.bb = byteBuffer;
	}

	private void service() throws IOException {
		try {
			ByteBuffer rbb = receive(); // Receive
			
			CommandParser comParser = new CommandParser();
			GeneralRequest generalReq = comParser.getData(this.bb);
			
			ProcessData processData = new ProcessData(mainDataStructure);
			//ResponseData responseData = processData.process(generalReq);
			/*
			responseData.getResponse().flip();
			System.out.println("Response - "+responseData.getResponse().get(0)+" - "+ responseData.getResponse().getShort(1) + " - " );
			switch (generalReq.getReqType()){
			case(GeneralSettings.CT_SEND_DATA):
				while (responseData.getResponse().hasRemaining()) 
					cio.write (responseData.getResponse());
				//cio.write(responseData.getResponse());
				break;
			default:
				break;
			}
*/		
			cio.close();
			
		
		} catch (IOException x) {
			String m = x.getMessage();
/*			if (!m.equals("Broken pipe")
					&& !m.equals("Connection reset by peer")) {
				System.err.println("RequestHandler: " + x.toString());
			}
*/			System.err.println("Second error: " + x.toString());
			cio.close();
		}
	}

	public  synchronized void run() {
		try {
			service();
		} catch (IOException x) {
			x.printStackTrace();
		}
	}

	ByteBuffer receive() throws IOException {

		bb.clear();
		while (cio.read (bb) > 0) {
			bb.flip(); // Make buffer readable
			}
		/*for (;;) {
			int read = cio.read();
			ByteBuffer bb = cio.getReadBuf();
			if (read < 0 || isReceived(bb) ) {
				bb.flip();
				return bb;
			}
		}
		*/
		return bb;
	}

	private boolean isReceived(ByteBuffer bb){
		return bb.get(bb.position())==0;
	
	}
}
